<template>
  <div class="app-container">
    <!-- 商品不存在 -->
    <div v-if="!patchInfo" class="error-container">
      <i class="el-icon-warning-outline"></i>
      <p>该商品不存在</p>
    </div>

    <!-- 商品存在 -->
    <template v-else>
      <div class="page-header">
        <div class="title1">金钗石斛质量追溯系统</div>
        <div class="title">该产品有溯源信息--{{ qrStatus }}</div>
      </div>
      <div
        class="buy-container"
        @click="handleBuy"
        v-if="qrStatus === '正在售卖'"
      >
        点击购买
      </div>
      <div class="buy-container" @click="handleMonitor">查看监控</div>
      <!-- 客户信息弹窗 -->
      <el-dialog
        title="填写客户信息"
        :visible.sync="dialogVisible"
        width="90%"
        max-width="600px"
        custom-class="responsive-dialog"
        @close="clearForm"
      >
        <el-form
          :model="customerInfo"
          :rules="rules"
          ref="customerForm"
          label-width="100px"
        >
          <el-form-item label="客户名称" prop="qrCustomerName">
            <el-input v-model="customerInfo.qrCustomerName"></el-input>
          </el-form-item>
          <el-form-item label="客户电话" prop="qrCustomerPhone">
            <el-input v-model="customerInfo.qrCustomerPhone"></el-input>
          </el-form-item>
          <el-form-item label="客户地址" prop="qrCustomerAddress">
            <el-input v-model="customerInfo.qrCustomerAddress"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>

      <div class="content">
        <div class="section-header">
          <i class="el-icon-message section-icon"></i>
          <span>基本信息</span>
        </div>
        <!-- 基本信息 -->
        <div class="info-section">
          <div @click="toggleExpand('basic')" class="section-content">
            <div class="image-container">
              <el-image
                v-if="imageList.patchImage.length"
                :src="imageList.patchImage[0]"
                class="patch-image"
                :preview-src-list="imageList.patchImage"
              ></el-image>
            </div>
            <div class="text-content">
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >批次描述:</strong
                >{{ patchInfo.patchDescription }}
              </p>
            </div>
          </div>
        </div>

        <div class="section-header">
          <i class="el-icon-star-on section-icon"></i>
          <span>种苗繁育</span>
          <span class="date">{{
            formatDate(patchInfo.zhongmiao.zhongMiaoTime)
          }}</span>
        </div>
        <!-- 种苗繁育信息 -->
        <div class="info-section" v-if="patchInfo.zhongmiao">
          <div @click="toggleExpand('zhongmiao')" class="section-content">
            <div class="image-container">
              <el-image
                v-if="imageList.zhongmiaoImage.length"
                :src="imageList.zhongmiaoImage[0]"
                class="patch-image"
                :preview-src-list="imageList.zhongmiaoImage"
              ></el-image>
            </div>
            <div class="text-content">
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >繁育任务名称:</strong
                >{{ patchInfo.zhongmiao.zhongMiaoManagementName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >显示名称:</strong
                >{{ patchInfo.zhongmiao.zhongMiaoDisplayName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >种苗描述:</strong
                >{{ patchInfo.zhongmiao.zhongMiaoDescription }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >种苗来源地:</strong
                >{{ patchInfo.zhongmiao.zhongMiaoSourceLocation }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >种苗来源单位:</strong
                >{{ patchInfo.zhongmiao.zhongMiaoSourceUnit }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >种苗采购日期:</strong
                >{{ patchInfo.zhongmiao.zhongMiaoPurchaseDate }}
              </p>
            </div>
          </div>
        </div>

        <div class="section-header">
          <i class="el-icon-view section-icon"></i>
          <span>栽培</span>
          <span class="date">{{
            formatDate(patchInfo.zaipei.zaiPeiTime)
          }}</span>
        </div>
        <!-- 栽培信息 -->
        <div class="info-section" v-if="patchInfo.zaipei">
          <div @click="toggleExpand('zaipei')" class="section-content">
            <div class="image-container">
              <el-image
                v-if="imageList.zaipeiImage.length"
                :src="imageList.zaipeiImage[0]"
                class="patch-image"
                :preview-src-list="imageList.zaipeiImage"
              ></el-image>
            </div>
            <div class="text-content">
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >管理任务名称:</strong
                >{{ patchInfo.zaipei.zaiPeiManagementName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >显示名称:</strong
                >{{ patchInfo.zaipei.zaiPeiDisplayName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >栽培类型:</strong
                >{{ patchInfo.zaipei.zaiPeiType }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >种苗来源:</strong
                >{{ patchInfo.zaipei.zaiPeiSeedlingSource }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px">海拔:</strong
                >{{ patchInfo.zaipei.zaiPeiAltitude }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >遮荫程度:</strong
                >{{ patchInfo.zaipei.zaiPeiShadeDegree }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >栽培温度:</strong
                >{{ patchInfo.zaipei.zaiPeiTemperature }}摄氏度
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px">水源:</strong
                >{{ patchInfo.zaipei.zaiPeiWaterSource }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >空气质量:</strong
                >{{ patchInfo.zaipei.zaiPeiAirQuality }}
              </p>
            </div>
          </div>
        </div>

        <div class="section-header">
          <i class="el-icon-search section-icon"></i>
          <span>采收</span>
          <span class="date">{{
            formatDate(patchInfo.caishou.caiShouTime)
          }}</span>
        </div>
        <!-- 采收信息 -->
        <div class="info-section" v-if="patchInfo.caishou">
          <div @click="toggleExpand('caishou')" class="section-content">
            <div class="image-container">
              <el-image
                v-if="imageList.caishouImage.length"
                :src="imageList.caishouImage[0]"
                class="patch-image"
                :preview-src-list="imageList.caishouImage"
              ></el-image>
            </div>
            <div class="text-content">
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >管理任务名称:</strong
                >{{ patchInfo.caishou.caiShouManagementName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >显示名称:</strong
                >{{ patchInfo.caishou.caiShouDisplayName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >采收类型:</strong
                >{{ patchInfo.caishou.caiShouType }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >采收地点:</strong
                >{{ patchInfo.caishou.caiShouLocation }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >采收描述:</strong
                >{{ patchInfo.caishou.caiShouDescription }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px">重量:</strong
                >{{ patchInfo.caishou.caiShouWeight }}
              </p>
            </div>
          </div>
        </div>

        <div class="section-header">
          <i class="el-icon-box section-icon"></i>
          <span>加工</span>
          <span class="date">{{
            formatDate(patchInfo.jiaGong.jiaGongTime)
          }}</span>
        </div>
        <!-- 加工信息 -->
        <div class="info-section" v-if="patchInfo.jiaGong">
          <div @click="toggleExpand('jiaGong')" class="section-content">
            <div class="image-container">
              <el-image
                v-if="imageList.jiaGongImage.length"
                :src="imageList.jiaGongImage[0]"
                class="patch-image"
                :preview-src-list="imageList.jiaGongImage"
              ></el-image>
            </div>
            <div class="text-content">
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >管理任务名称:</strong
                >{{ patchInfo.jiaGong.jiaGongManagementName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >显示名称:</strong
                >{{ patchInfo.jiaGong.jiaGongDisplayName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >加工类型:</strong
                >{{ patchInfo.jiaGong.jiaGongType }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >加工流程描述:</strong
                >{{ patchInfo.jiaGong.jiaGongProcessDetails }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >加工地点:</strong
                >{{ patchInfo.jiaGong.jiaGongLocation }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >原料来源:</strong
                >{{ patchInfo.jiaGong.jiaGongSource }}
              </p>
            </div>
          </div>
        </div>

        <div class="section-header">
          <i
            style="color: greenyellow; width: 10px; height: 15px"
            class="el-icon-check section-icon"
          ></i>
          <span>质量检测</span>
          <span class="date">{{
            formatDate(patchInfo.zhilijiance.zhiLiJianCeTime)
          }}</span>
        </div>
        <!-- 质量检测信息 -->
        <div class="info-section" v-if="patchInfo.zhilijiance">
          <div @click="toggleExpand('zhilijiance')" class="section-content">
            <div class="image-container">
              <el-image
                v-if="imageList.zhilijianceImage.length"
                :src="imageList.zhilijianceImage[0]"
                class="patch-image"
                :preview-src-list="imageList.zhilijianceImage"
              ></el-image>
            </div>
            <div class="text-content">
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >任务管理名称:</strong
                >{{ patchInfo.zhilijiance.zhiLiJianCeManagementName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >检测项目名称:</strong
                >{{ patchInfo.zhilijiance.zhiLiJianCeTestName }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >检测过程描述:</strong
                >{{ patchInfo.zhilijiance.zhiLiJianCeTestProcess }}
              </p>
              <p>
                <strong style="color: #0037ff; font-size: 20px"
                  >检测结果:</strong
                >{{ patchInfo.zhilijiance.zhiLiJianCeTestResults }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { getPatchByQrCode } from "@/api/seedlingSys/patch";
import { updateQr } from "@/api/seedlingSys/qr";
import { parseTime } from "@/utils/ruoyi"; // 手动引入 parseTime 方法

export default {
  name: "PatchView",
  data() {
    return {
      patchInfo: null,
      section: this.$route.query.section || "basic",
      qrStatus: "",
      dialogVisible: false, // 控制弹窗显示和隐藏
      qrPatchID: null,
      qrProductionTime: null,
      qrUniqueCode: null,
      qrRetailerInfo: null,
      qrID: null, // 新增字段qrID
      customerInfo: {
        qrCustomerName: "",
        qrCustomerPhone: "",
        qrCustomerAddress: "",
      },
      rules: {
        qrCustomerName: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
        ],
        qrCustomerPhone: [
          { required: true, message: "请输入客户电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的11位电话号码",
            trigger: "blur",
          },
        ],
        qrCustomerAddress: [
          { required: true, message: "请输入客户地址", trigger: "blur" },
        ],
      },
      imageList: {}, // 修改为对象来存储不同部分的图片列表
    };
  },
  created() {
    console.log("parseTime exists:", typeof parseTime === "function"); // 使用手动引入的 parseTime
    const code = this.$route.query.code;
    if (code) {
      this.getPatchInfo(code);
    }
  },
  mounted() {
    const code = this.$route.query.code;
    if (code) {
      this.getPatchInfo(code);
    }
  },
  methods: {
    handleBuy() {
      this.dialogVisible = true;
    },
    // 购买方法
    clearForm() {
      this.$refs.customerForm.resetFields();
    },
    submitForm() {
      this.$refs.customerForm.validate((valid) => {
        if (valid) {
          this.updateQrInfo();
        } else {
          console.log("表单验证失败!");
          return false;
        }
      });
    },
    updateQrInfo() {
      // 获取当前二维码的 ID
      const qrID = this.qrID;
      if (!qrID) {
        this.$message.error("二维码ID未正确获取，请刷新页面重试");
        return;
      }

      // 构造请求数据
      const payload = {
        ...this.customerInfo,
        qrPatchID: this.qrPatchID,
        qrID: qrID, // 添加 qrID 到 payload 中
      };
      updateQr(payload) // 这里应该使用qrID而不是qrCode
        .then((response) => {
          if (response.code === 200) {
            this.$message.success("客户信息填写成功！");
            this.qrStatus = "已售卖";
            this.dialogVisible = false;
          } else {
            this.$message.error(response.msg || "客户信息填写失败");
          }
        })
        .catch((error) => {
          console.error("接口调用失败:", error);
          this.$message.error("客户信息填写失败");
        });
    },
    // 监控方法
    handleMonitor() {
      this.$router.push({ name: "monitor" });
    },
    //查看详细信息方法
    toggleExpand(index) {
       this.$router.push({
    name: "PatchDetail",
    query: {
      code: this.$route.query.code,
      section: index, // 使用 index 参数代替 section
    },
  });
    },

    getPatchInfo(code) {
      getPatchByQrCode(code)
        .then((response) => {
          if (response.code === 200) {
            this.patchInfo = response.data;
            console.log(this.patchInfo);
            this.qrID = response.data.qrId; // 新增字段qrID

            console.log(this.qrID);
            // 赋值新增字段
            this.qrPatchID = response.data.patchID;
            this.qrProductionTime = response.data.qrProductionTime;
            this.qrUniqueCode = response.data.qrUniqueCode;
            this.qrRetailerInfo = response.data.qrRetailerInfo;
            console.log(
              this.patchInfo,
              this.qrPatchID,
              this.qrProductionTime,
              this.qrUniqueCode,
              this.qrRetailerInfo
            );

            // 处理图片字段
            this.imageList.patchImage = this.patchInfo.patchImage
              ? this.patchInfo.patchImage
                  .split(",")
                  .map((image) => "http://localhost:8080" + image.trim())
              : [];
            this.imageList.zhongmiaoImage = this.patchInfo.zhongmiao
              .zhongMiaoImage
              ? this.patchInfo.zhongmiao.zhongMiaoImage
                  .split(",")
                  .map((image) => "http://localhost:8080" + image.trim())
              : [];
            this.imageList.zaipeiImage = this.patchInfo.zaipei.zaiPeiImage
              ? this.patchInfo.zaipei.zaiPeiImage
                  .split(",")
                  .map((image) => "http://localhost:8080" + image.trim())
              : [];
            this.imageList.caishouImage = this.patchInfo.caishou.caiShouImage
              ? this.patchInfo.caishou.caiShouImage
                  .split(",")
                  .map((image) => "http://localhost:8080" + image.trim())
              : [];
            this.imageList.jiaGongImage = this.patchInfo.jiaGong.jiaGongImage
              ? this.patchInfo.jiaGong.jiaGongImage
                  .split(",")
                  .map((image) => "http://localhost:8080" + image.trim())
              : [];
            this.imageList.zhilijianceImage = this.patchInfo.zhilijiance
              .zhiLiJianCeImage
              ? this.patchInfo.zhilijiance.zhiLiJianCeImage
                  .split(",")
                  .map((image) => "http://localhost:8080" + image.trim())
              : [];
            console.log(this.imageList);

            // 根据二维码的字段决定状态
            const qrCustomerName = response.data.qrCustomerName;
            const qrCustomerPhone = response.data.qrCustomerPhone;
            const qrCustomerAddress = response.data.qrCustomerAddress;
            console.log(qrCustomerName, qrCustomerPhone, qrCustomerAddress);
            if (
              qrCustomerName === null &&
              qrCustomerPhone === null &&
              qrCustomerAddress === null
            ) {
              this.qrStatus = "正在售卖";
            } else {
              this.qrStatus = "已售卖";
            }
          } else {
            this.$message.error(response.msg || "获取数据失败");
          }
        })
        .catch((error) => {
          console.error("接口调用失败:", error);
          this.$message.error("获取数据失败");
        });
    },
    formatDate(date) {
      if (!date) return "";
      return parseTime(date, "{y}-{m}-{d}"); // 使用手动引入的 parseTime
    },
    fillCustomerInfo() {
      this.$message.info("填写客户信息功能开发中...");
      // 在这里可以调用填写信息的逻辑或跳转到相关页面
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.error-container {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.error-container i {
  font-size: 48px;
  margin-bottom: 10px;
}

.page-header {
  background-color: #2252ff;
  color: white;
  height: 180px;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 10px;
}
.buy-container {
  width: 100%;
  height: 52px;
  background-color: #ff2222;
  color: white;
  text-align: center;
  font-size: 24px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  letter-spacing: 4px;
}
.title1 {
  font-size: 15px;
  color: aliceblue;
  text-align: center; /* 居中对齐 */
}

.title {
  margin-top: 70px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.info-section {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  align-items: center;
  width: 220px;
  height: 40px;
  margin-bottom: 10px;
  border-radius: 40px; /* 使容器圆角 */
  padding: 10px 15px; /* 调整按钮内部间距 */
  background-color: #ffffff; /* 设置背景为橙色 */
  color: #ff8d22; /* 设置文字颜色为白色 */
  font-size: 22px; /* 调整文字大小 */
  font-weight: bold; /* 设置文字加粗 */
  box-shadow: 1px 1px 1px 1px rgba(255, 165, 86, 0.2); /* 添加阴影效果 */
}

.section-icon {
  font-size: 20px;
  margin-right: 10px;
  color: #409eff;
}

.date {
  margin-left: auto;
  color: #ff8d22;
  font-size: 13px;
}

.section-content {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  color: #000000;
}
.image-container {
  flex: 3;
  border-radius: 100px;
}
.patch-image {
  width: 70px;
  height: 70px;
  border-radius: 100px;
}
.text-content {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  color: #000000;
  display: -webkit-box; /* 将容器转换为弹性盒子模型 */
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 设置最多显示的行数 */
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 7;
  font-weight: bold;
  font-size: 17px;
  min-height: 0; /* 确保在 Firefox 中也能正常工作 */
}
.responsive-dialog {
  max-width: 90vw; /* 弹窗最大占屏幕宽度 */
  margin: auto;
}

.el-dialog__body {
  max-height: 70vh; /* 弹窗内部内容最大高度 */
  overflow-y: auto; /* 内容过多时支持滚动 */
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px; /* 调整表单的间隔 */
}

.el-input {
  width: 100%; /* 输入框宽度占满 */
}
</style>
